<?php

namespace app\common\model\distribute;

use app\common\model\hfztcy\LibConfig;
use app\common\model\hfztcy\LibOrderVipAuth;
use common\Common;

class StoreUserCommission extends base
{
    public function getCommissionByStoreUserId()
    {
        $orderVipAuthModel = new LibOrderVipAuth();
        $result = [];
        $this->write_file('-----------门店-----------');
        if (isset($this->orderInfo['store']) && $this->orderInfo['store_id']) {
            $this->write_file('门店ID：' . $this->orderInfo['store_id']);
            // 绑定的门店用户
            $findMemberRes = $this->member->findMember(['user_id' => $this->orderInfo['store']['uid']]);
            if ($findMemberRes['errorCode'] == 0)
            {
                // 门店绑定的用户信息
                $memberInfo = $findMemberRes['data'];

                // 栏目认证配置参数
                $configModel = new LibConfig();
                $findConfigRes = $configModel->findConfig(['item_key' => 'vip_video_auth_rate']);
                $rateList = json_decode($findConfigRes['data']['item_value'], true);
                if ($rateList['store']) {
                    // 扣除制作费
                    $amount = $this->orderInfo['amount'] - (float)$rateList['amount'];
                    if ($amount <= 0) {
                        return $result;
                    }

                    $store_point_user_rate = (float)$rateList['store_point_user'];//门店抽取直推红娘多少分润比例
                    // 判断是否为门店派单
                    if ($this->orderInfo['is_offline'] == 1) {//表示用户指定门店
                        $rate = (float)$rateList['store'] + $store_point_user_rate;
                    } else {//表示后台指定门店
                        $rate = (float)$rateList['store'];
                    }

                    // 1、门店抽取红娘直推分润比例
                    if ($this->orderInfo['is_offline'] == 1)
                    {
                        $this->write_file('1、门店抽取红娘直推分润比例');
                        $findDirectMemberRes = $this->member->findMember(['user_id' => $this->orderInfo['store']['uid']]);
                        if ($findDirectMemberRes['errorCode'] == 0)
                        {
                            $directMemberInfo = $findDirectMemberRes['data'];
                            $store_point_user_commission_money = ($amount * $store_point_user_rate);
                            $store_point_user_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $store_point_user_commission_money), 0, -1));
                            $this->write_file('门店抽取直推红娘佣金：' . $store_point_user_commission_money);
                            $data = $this->getData($directMemberInfo, $store_point_user_commission_money);
                            $this->member->updateMember(['user_id' => $this->orderInfo['store']['uid']], $data);
                            $sql1 = $this->member->getLastSql();
                            $this->write_file('更新会员佣金SQL：' . $sql1);
                            $this->user->updateUser(['id' => $this->orderInfo['store']['uid']], $data);
                            $sql2 = $this->user->getLastSql();
                            $this->write_file('更新会员佣金SQL：' . $sql2);
                            if ($this->curPayUserInfo['errorCode'] == 0) {
                                $describe = $this->curPayUserInfo['data']['username'] . "栏目认证，门店从直推红娘抽拥：{$store_point_user_commission_money}";
                            } else {
                                $describe = "栏目认证，门店从直推红娘抽拥：{$store_point_user_commission_money}";
                            }
                            $sql3 = $this->extracted($store_point_user_commission_money, $directMemberInfo['balance'], $this->orderInfo['store']['uid'], $describe);
                            $this->write_file('门店抽取红娘佣金记录SQL：' . $sql3);

                            // 更新订单
                            $findOrderVipAuthRes = $orderVipAuthModel->findOrder(['order_id' => $this->orderInfo['id']]);
                            $pt_commission_money_list = [
                                $findOrderVipAuthRes['data']['zt_commission_money'],
                                $findOrderVipAuthRes['data']['jt_commission_money'],
                                $findOrderVipAuthRes['data']['shi_commission_money'],
                                $findOrderVipAuthRes['data']['xian_commission_money'],
                                $findOrderVipAuthRes['data']['kf_commission_money'],
                                $findOrderVipAuthRes['data']['px_commission_money'],
                                abs($store_point_user_commission_money),
                            ];
                            $pt_commission_money = $amount - array_sum($pt_commission_money_list);
                            $orderVipAuthModel->updateOrder(['order_id' => $this->orderInfo['id']], [
                                'md_give_red_mother_commission_money' => abs($store_point_user_commission_money),//门店抽取红娘佣金
                                'pt_commission_money' => $pt_commission_money
                            ]);
                        } else {
                            $this->write_file('门店未绑定用户或者绑定的用户不存在' );
                        }
                    }
                    // 2、门店自身的佣金比例
                    $this->write_file('2、门店自身的佣金比例');
                    $store_commission_money_self_total = $amount * (float)$rateList['store'];//门店自身佣金比例
                    $store_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $store_commission_money_self_total), 0, -1));

                    $add_commission_record1_sql = $this->extracted($store_commission_money, $memberInfo['balance'], $this->orderInfo['store']['uid']);
                    $this->write_file('门店本身的佣金记录SQL：' . $add_commission_record1_sql);

                    $findOrderVipAuthRes = $orderVipAuthModel->findOrder(['order_id' => $this->orderInfo['id']]);
                    $pt_commission_money_list = [
                        $findOrderVipAuthRes['data']['zt_commission_money'],
                        $findOrderVipAuthRes['data']['jt_commission_money'],
                        $findOrderVipAuthRes['data']['md_give_red_mother_commission_money'],
                        $findOrderVipAuthRes['data']['shi_commission_money'],
                        $findOrderVipAuthRes['data']['xian_commission_money'],
                        $findOrderVipAuthRes['data']['kf_commission_money'],
                        $findOrderVipAuthRes['data']['px_commission_money'],
                        abs($store_commission_money),
                    ];
                    $pt_commission_money = $amount - array_sum($pt_commission_money_list);
                    $orderVipAuthModel->updateOrder(['order_id' => $this->orderInfo['id']], [
                        'store_user_id' => $this->orderInfo['store']['uid'],
                        'md_commission_money' => abs($store_commission_money),
                        'pt_commission_money' => $pt_commission_money
                    ]);
                    $this->write_file('门店本身的佣金：' . $store_commission_money);
                    $findMemberRes = $this->member->findMember(['user_id' => $this->orderInfo['store']['uid']]);
                    $memberInfo = $findMemberRes['data'];
                    $data = $this->getData($memberInfo, $store_commission_money);
                    $this->member->updateMember(['user_id' => $this->orderInfo['store']['uid']], $data);
                    $update_store1_sql = $this->member->getLastSql();
                    $this->write_file('更新会员佣金SQL：' . $update_store1_sql);
                    $this->user->updateUser(['id' => $this->orderInfo['store']['uid']], $data);
                    $update_store2_sql = $this->user->getLastSql();
                    $this->write_file('更新会员佣金SQL：' . $update_store2_sql);

                    // 给门店上级增加佣金
                    $update_store_parent1_sql = $update_store_parent2_sql = $add_commission_record2_sql = '';
                    if ($rateList['store_direct_user'])
                    {
                        $this->write_file('给门店上级增加佣金');
                        $store_commission_money_total = ($amount * $rate);//门店自身佣金比例+门店抽取直推红娘的佣金比例
                        $this->write_file('门店总佣金：' . $store_commission_money_total);
                        $res = $this->getStoreParentUserCommission($store_commission_money_total, $rateList,$amount);
                        if ($res) {
                            $update_store_parent1_sql = $res['update_store_parent1_sql'];
                            $update_store_parent2_sql = $res['update_store_parent2_sql'];
                            $add_commission_record2_sql = $res['add_commission_record2_sql'];
                        }
                    }

                    $result[] = [
                        'update_store1_sql' => $update_store1_sql,
                        'update_store2_sql' => $update_store2_sql,
                        'create_member_commission_record_sql' => $add_commission_record1_sql,
                        'update_store_parent1_sql' => $update_store_parent1_sql,
                        'update_store_parent2_sql' => $update_store_parent2_sql,
                        'add_commission_record2_sql' => $add_commission_record2_sql,
                    ];
                } else {
                    $this->write_file('配置比例未设置' );
                }
            } else {
                $this->write_file('绑定的门店用户不存在' );
            }
        } else {
            $this->write_file('门店不存在' );
        }
        return $result;
    }

    // 门店上级推荐人佣金 门店上级推荐人要么获得订单总额的2%收益 要么是获得3%收益
    private function getStoreParentUserCommission($store_commission_money, $rateList,$amount)
    {
        $result = [];
        // 绑定的店铺用户
        $findUserRes = $this->user->findUser(['id' => $this->orderInfo['store']['uid']]);
        if ($findUserRes['errorCode'] == 0)
        {
            // 获取上级推荐人
            $findParentUserRes = $this->user->findUser(['id' => $this->orderInfo['store']['user_id']]);
            if ($findParentUserRes['errorCode'] == 0)
            {
                // 上级推荐人信息
                $memberInfo = $findParentUserRes['data'];
                $store_direct_user = (float)$rateList['store_direct_user'];
                $this->write_file('上级推荐人分润比例：' . $store_direct_user);
                // 门店上级佣金
                $store_parent_user_commission_money = $store_commission_money * $store_direct_user;
                $this->write_file('门店上级佣金：' . $store_parent_user_commission_money);
                $orderVipAuthModel = new LibOrderVipAuth();
                $findOrderVipAuthRes = $orderVipAuthModel->findOrder(['order_id' => $this->orderInfo['id']]);
                $pt_commission_money_list = [
                   $findOrderVipAuthRes['data']['zt_commission_money'],
                   $findOrderVipAuthRes['data']['jt_commission_money'],
                   $findOrderVipAuthRes['data']['md_commission_money'],
                   $findOrderVipAuthRes['data']['md_give_red_mother_commission_money'],
                   $findOrderVipAuthRes['data']['shi_commission_money'],
                   $findOrderVipAuthRes['data']['xian_commission_money'],
                   $findOrderVipAuthRes['data']['kf_commission_money'],
                   $findOrderVipAuthRes['data']['px_commission_money'],
                    abs($store_parent_user_commission_money),
                ];
                $pt_commission_money = $amount - array_sum($pt_commission_money_list);
                // 更新订单
                $orderVipAuthModel->updateOrder(['order_id' => $this->orderInfo['id']], [
                    'store_parent_user_id' => $this->orderInfo['store']['user_id'],
                    'store_parent_user_commission_money' => abs($store_parent_user_commission_money),
                    'pt_commission_money' => $pt_commission_money
                ]);
                // 更新会员余额
                $data = $this->getData($memberInfo, $store_parent_user_commission_money);
                $this->member->updateMember(['user_id' => $this->orderInfo['store']['user_id']], $data);
                $update_store_parent1_sql = $this->member->getLastSql();
                $this->write_file('更新会员佣金SQL：' . $update_store_parent1_sql);
                $this->user->updateUser(['id' => $this->orderInfo['store']['user_id']], $data);
                $update_store_parent2_sql = $this->user->getLastSql();
                $this->write_file('更新会员佣金SQL：' . $update_store_parent2_sql);
                // 添加佣金记录
                if ($this->curPayUserInfo['errorCode'] == 0) {
                    $describe = $this->curPayUserInfo['data']['username'] . "栏目认证，门店推荐人佣金：{$store_parent_user_commission_money}";
                } else {
                    $describe = "栏目认证，门店推荐人佣金：{$store_parent_user_commission_money}";
                }
                $add_commission_record1_sql = $this->extracted($store_parent_user_commission_money, $memberInfo['balance'], $this->orderInfo['store']['user_id'], $describe);
                $this->write_file('佣金记录SQL：' . $add_commission_record1_sql);
                return [
                    'update_store_parent1_sql' => $update_store_parent1_sql,
                    'update_store_parent2_sql' => $update_store_parent2_sql,
                    'add_commission_record2_sql' => $add_commission_record1_sql,
                ];
            } else {
                $this->write_file('上级推荐人不存在' );
            }
        } else {
            $this->write_file('绑定的店铺用户不存在' );
        }
        return $result;
    }

    private function getData($memberInfo, $commission)
    {
        $total_balance = (float)$memberInfo['total_balance'] + (float)$commission;//累计佣金
        $balance = (float)$memberInfo['balance'] + (float)$commission;//可提现佣金
        $commission = (float)$memberInfo['commission'] + (float)$commission;//冻结佣金
        if ($this->type == 2 || $this->type == 3) {//当订单类型是 【红娘认证】【栏目认证】，所得金额进入冻结佣金字段
            $data['commission'] = $commission;
        } else {
            $data = [
                'total_balance' => $total_balance,
                'balance' => $balance,
            ];
        }
        return $data;
    }

    private function extracted($money, $balance, $userId, $describe = '')
    {
        $sql = '';
        if (floatval($money) > 0) {
            $type = $this->orderInfo['type'];
            $typeStr = '';
            if ($type == 0) $typeStr = '付费看视频';
            if ($type == 1) $typeStr = '购买VIP套餐';
            if ($type == 2) $typeStr = '栏目认证';
            if ($type == 3) $typeStr = '红娘认证';
            if ($describe) {
                $info = $describe;
            } else {
                $curPayUser = $this->curPayUserInfo;
                if ($curPayUser['errorCode'] == 0) {
                    $info = $curPayUser['data']['username'] . $typeStr . '，可得佣金：' . $money;
                } else {
                    $info = $typeStr . '，可得佣金：' . $money;
                }
            }
            $data = [];
            $data['user_id'] = $userId;
            $data['describe'] = $info;
            $data['before_balance'] = $balance;
            $data['amount'] = $money;
            $data['add_time'] = Common::getTime();
            $data['order_id'] = $this->orderInfo['id'];
            $data['pay_user_id'] = $this->orderInfo['user_id'];
            $data['type'] = $this->type;
            $data['zj_state'] = in_array($this->type, [2, 3]) ? 1 : 0;//佣金状态 0可提现 1冻结中 2已失效
            $data['order_info'] = json_encode($this->orderInfo, JSON_UNESCAPED_UNICODE);
            $this->balanceRecords->addCommissionRecords($data);
            $sql = $this->balanceRecords->getLastSql();
        }
        return $sql;
    }
}